Home:ALL Converter>How to fix "No compatible definition found for type 'Context'" from Koin lib?

How to fix "No compatible definition found for type 'Context'" from Koin lib?

Ask Time:2018-09-15T20:00:24         Author:LunaVulpo

Json Formatter

I just started using Koin lib in an android (to replace Dagger 2) project which was prepared for tests. I have an issue with the android app context in module:

val M = module {
   val ctx = androidApplication() //here error
}

Koin is started in App class:

import android.app.Application
import android.content.Context
import org.koin.android.ext.android.startKoin

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        startKoin(this, listOf(M))
    }
}

I get log:

D/App: onCreate()
I/KOIN: [context] create
E/KOIN: [ERROR] - Error while resolving instance for class 'android.app.Application' - error: org.koin.error.NoBeanDefFoundException: No compatible definition found for type 'Application'. Check your module definition 

and the app crashes. Did I miss something in the configuration of Koin? In the target project, I have a few modules which deeply depend on application context. And I don't want to use a global reference to this context.

Author:LunaVulpo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/52344507/how-to-fix-no-compatible-definition-found-for-type-context-from-koin-lib
Abhishek Dubey :

Solution is easy but not so obvious.\n\nSomehow Android Studio imports standalone startKoin function instead of specific android function.\n\nSo you had to replace\n\nimport org.koin.standalone.StandAloneContext.startKoin\n\n\nTo\n\nimport org.koin.android.ext.android.startKoin\n\n\nin Application class \n\nDo tell if this works or not.",
2018-09-15T12:09:04
Niccolò Passolunghi :

Try not to create a val for the applicationAndroid() context but use it directly inside the factory/single closure as a parameter for one of your dependencies.\nWhat I'm doing in my project is something like:\n\n\n\nval appModule = module(override = true) {\n factory<Navigator> { MyNavigator(androidApplication()) }\n}\n\n\nwhere the MyNavigator class is:\n\n\n\nclass MyNavigator(private val context: Context): Navigator {\n\n override fun goToDetail(detailId: String) {\n context.startActivity(DetailActivity.getIntent(context, detailId))\n }\n}\n\n\n\n\np.s.: I did also some experiments with Koin 1.0.0 and I noticed that you can also write something like:\n\n\n\nval appModule = module(override = true) {\n factory<Navigator> { MyNavigator(get()) }\n}\n\n\nThat get() will retrieve the context for you even if there's no dependency in the graph for a Context instance; neither a factory nor a singleton. It might be that Koin does something behind the scenes. I tried to use it with different type of dependencies and it aways works.",
2018-09-18T15:19:33
yy